<template>
 <div>
     <el-form :model="user" :rules="rules" ref='ruleForm' label-width="100px">
        <el-form-item label="用户名" prop="username">
            <el-input v-model="user.username" placeholder="" v-on:blur='show'></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
            <el-input v-model="user.password" placeholder=""></el-input>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
            <el-input v-model="user.code" placeholder=""></el-input>
            <img v-show="isshow"  :src="imagesrc" v-on:click="getimage" alt="验证码" width="100">
        </el-form-item>
        <el-form-item >
            <el-button type="primary" @click="reg">注册</el-button>
        </el-form-item>
     </el-form>


 </div>
</template>

<script>
export default {
 data() {
  var checkpass = (rule, value, callback) => {
      if(value ===''){
          return callback(new Error('密码不能为空'))
      }else{
          if(value.length<6){
              return callback(new Error('密码不能少于六个字符'))
          }else{
              callback();
          }
      }
  }
  return {
    user:{
        username:'',
        password:'',
        code:'',
    },
    imagesrc:'',
    isshow:false,
        rules: {
          username: [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 6, message: '长度不少于6个字符', trigger: 'blur' }
          ],
          password:[
               { validator : checkpass , trigger:'blur'}
          ],
          code:[
            { required: true, message: '请输入验证码', trigger: 'blur' },

          ]


        }
  }
 },
 components: {

 },
 methods: {
     reg(){
         console.log(this.user)
        this.$refs['ruleForm'].validate((valid) => {
          if (valid) {
              this.axios({
                  url:'http://127.0.0.1:8000/register/',
                  method:'post',
                  data:this.user,
              }).then(res=>{
                  if(res.data.code==200){
                      this.$message('注册成功')
                      this.$router.push({name:'login'})
                  }else if(res.data.code==301){
                      this.$message('验证码错误')
                  }else{
                      this.$message('注册失败')
                  }
              })
          } else {
            this.$message('注册失败');
            return false;
          }
        });
     },
     show(){
         this.isshow=true;
         this.imagesrc = 'http://127.0.0.1:8000/image/?username='+ this.user.username
         
     },
    getimage(){
        var code = Math.random();
        this.imagesrc = "http://127.0.0.1:8000/image/?username=" + this.user.username + "&" + code;
    },

 },
}
</script>
